package com.valuegroup.smarttodo.ui.todo.habit;

import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.PopupMenu;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.model.AppStatus;
import com.valuegroup.smarttodo.data.model.HabitEvent;
import com.valuegroup.smarttodo.data.model.HabitOrderRelate;
import com.valuegroup.smarttodo.plugins.pickdialog.DatePickDialog;
import com.valuegroup.smarttodo.plugins.pickdialog.DateUtils;
import com.valuegroup.smarttodo.plugins.pickdialog.OnCustomSureLisener;
import com.valuegroup.smarttodo.plugins.pickdialog.OnSureLisener;
import com.valuegroup.smarttodo.plugins.pickdialog.bean.DateType;
import com.valuegroup.smarttodo.ui.BaseActivity;
import com.valuegroup.smarttodo.util.AlertUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 习惯项设定
 * 设定重复规则和截止时间
 */
public class HabitRuleSetActivity extends BaseActivity {

    @BindView(R.id.btnBack)
    ImageButton btnBack;
    @BindView(R.id.btnSave)
    TextView btnSave;
    @BindView(R.id.labHeaderTitle)
    TextView labHeaderTitle;
    @BindView(R.id.labRpeartType)
    TextView labRpeartType;
    @BindView(R.id.btnRepeatType)
    LinearLayout btnRepeatType;
    @BindView(R.id.labIndate)
    TextView labIndate;
    @BindView(R.id.btnIndate)
    LinearLayout btnIndate;
    @BindView(R.id.labFirst)
    TextView labFirst;
    @BindView(R.id.btnFirst)
    LinearLayout btnFirst;
    @BindView(R.id.listSignin)
    RecyclerView habitSigninRecycler;
    @BindView(R.id.labBeginDt)
    TextView labBeginDt;

    private Long DATA_ID;
    private Long orderId;
    private Integer DATA_POSITION;
    private HabitOrderRelate DATA;
    private PopupMenu filterMenu;
    private HabitSigninAdapter habitSigninAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_habitorder_rule_set);
        ButterKnife.bind(this);
        initView();
        initData();
    }

    private void initData() {
        DATA_ID = getIntent().getLongExtra(PARAMS_KEY, 0);
        orderId = getIntent().getLongExtra("orderId", 0);

        DATA_POSITION = getIntent().getIntExtra(PARAMS_POSITION, 0);
        DATA = ServiceFactory.getInstance().getHabitService().getHabitOrderRelateDao().load(DATA_ID);

        if (DATA_ID != 0 && DATA == null) {
            AlertUtils.showToast(getApplicationContext(), R.string.not_found_record);
            finish();
            return;
        }

        labBeginDt.setText(DateUtils.date2str(DATA.getBeginDt(), DateUtils.F40));
        labIndate.setText(String.format(getResources().getString(R.string.habit_deadline), DateUtils.date2str(DATA.getEndDt(), DateUtils.F40)));
        switch (DATA.getRepeatType()) {
            case AppStatus.RepeatType.EVERYDAY:
                // 每天
                btnFirst.setVisibility(View.GONE);
                labRpeartType.setText(getResources().getText(R.string.habit_repeat_m1));
                break;
            case AppStatus.RepeatType.EVERYWEEK:
                // 每周
                btnFirst.setVisibility(View.VISIBLE);

                // 默认为当前日期
                labFirst.setText(DateUtils.ARR_WEEKS[DATA.getRepeatFirst()]);
                labRpeartType.setText(getResources().getText(R.string.habit_repeat_m2));
                break;
            case AppStatus.RepeatType.WORKDAY:
                btnFirst.setVisibility(View.GONE);
                labRpeartType.setText(getResources().getText(R.string.habit_repeat_m3));
                // 每个工作日
                break;
            case AppStatus.RepeatType.UNWORKDAY:
                btnFirst.setVisibility(View.GONE);
                labRpeartType.setText(getResources().getText(R.string.habit_repeat_m5));
                // 每个周末
                break;
            case AppStatus.RepeatType.EVERYMONTH:
                // 每月
                btnFirst.setVisibility(View.VISIBLE);
                labFirst.setText(String.format(getResources().getString(R.string.habit_day_fmt), DATA.getRepeatFirst()));
                labRpeartType.setText(getResources().getText(R.string.habit_repeat_m4));
                break;
        }

        initListData();
    }


    private void initListData() {

        // 修改为通过习惯项直接查询，这样可以查询到历史打卡数据
        //List<HabitEvent> data = ServiceFactory.getInstance().getHabitService().findHabitEventForRelate(DATA_ID);
        List<HabitEvent> data = ServiceFactory.getInstance().getHabitService().findHabitEvent(DATA.getHid());

        // 刷新列表数据
        habitSigninAdapter.refreshListData(data);

        // 跳转至当前日期所在位置
        habitSigninRecycler.post(new Runnable() {
            @Override
            public void run() {
                String today = DateUtils.date2str(new Date(), DateUtils.F40);
                for (int position = 0; position < data.size(); position++) {
                    if (DateUtils.date2str(data.get(position).getScheduleDt(), DateUtils.F40).equals(today)) {
                        //habitSigninRecycler.smoothScrollToPosition(i);
                        //平滑到操作项
                        ((LinearLayoutManager) habitSigninRecycler.getLayoutManager()).scrollToPositionWithOffset(position, 0);
                        break;
                    }
                }
            }
        });
    }

    private void initView() {
        // 起始日期或起始星期
        btnFirst.setVisibility(View.GONE);

        // 重复类型菜单
        filterMenu = new PopupMenu(this, labRpeartType);
        filterMenu.inflate(R.menu.menu_habit_repeat);
        filterMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.m1:
                        // 每天
                        DATA.setRepeatType(AppStatus.RepeatType.EVERYDAY);
                        btnFirst.setVisibility(View.GONE);
                        break;
                    case R.id.m2:
                        // 每周
                        DATA.setRepeatType(AppStatus.RepeatType.EVERYWEEK);
                        btnFirst.setVisibility(View.VISIBLE);

                        // 默认为当前日期
                        DATA.setRepeatFirst(DateUtils.getWeek(null));
                        labFirst.setText(DateUtils.ARR_WEEKS[DATA.getRepeatFirst()]);
                        break;
                    case R.id.m3:
                        DATA.setRepeatType(AppStatus.RepeatType.WORKDAY);
                        btnFirst.setVisibility(View.GONE);
                        // 每个工作日
                        break;
                    case R.id.m5:
                        DATA.setRepeatType(AppStatus.RepeatType.UNWORKDAY);
                        btnFirst.setVisibility(View.GONE);
                        // 每个周末
                        break;
                    case R.id.m4:
                        // 每月
                        DATA.setRepeatType(AppStatus.RepeatType.EVERYMONTH);
                        btnFirst.setVisibility(View.VISIBLE);
                        DATA.setRepeatFirst(DateUtils.getDay(new Date()));
                        labFirst.setText(String.format(getResources().getString(R.string.habit_day_fmt), DATA.getRepeatFirst()));
                        break;
                }
                labRpeartType.setText(item.getTitle());
                return true;
            }
        });

        // 起始日期或星期
        btnFirst.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DateType type = DateType.TYPE_CUSTOM_DAY;
                if (DATA.getRepeatType() == AppStatus.RepeatType.EVERYWEEK) {
                    type = DateType.TYPE_CUSTOM_WEEK;
                }

                DatePickDialog d = new DatePickDialog(HabitRuleSetActivity.this);
                d.setType(type);
                d.setStartData(DATA.getRepeatFirst());
                d.setOnCustomSureLisener(new OnCustomSureLisener() {
                    @Override
                    public void onSure(Object val) {
                        int value = (int) val;
                        if (DATA.getRepeatType() == AppStatus.RepeatType.EVERYWEEK) {
                            labFirst.setText(DateUtils.ARR_WEEKS[value]);
                        } else {
                            labFirst.setText(String.format(getResources().getString(R.string.habit_day_fmt), value));
                        }
                        DATA.setRepeatFirst(value);
                    }
                });
                d.show();
            }
        });

        btnRepeatType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                filterMenu.show();
            }
        });

        // 选择截止日期或截止次数
        btnIndate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DatePickDialog dialog = new DatePickDialog(HabitRuleSetActivity.this);
                dialog.setType(DateType.TYPE_YMD);
                dialog.setStartDate(DATA.getEndDt());
                dialog.setOnSureLisener(new OnSureLisener() {
                    @Override
                    public void onSure(Date date) {
                        // 截止时间
                        DATA.setEndDt(date);
                        labIndate.setText(String.format(getResources().getString(R.string.habit_deadline), DateUtils.date2str(date, DateUtils.F40)));
                    }
                });
                dialog.show();
            }
        });

        habitSigninAdapter = new HabitSigninAdapter(HabitRuleSetActivity.this, new ArrayList<>());
        habitSigninRecycler.setHasFixedSize(true);
        habitSigninRecycler.setLayoutManager(new LinearLayoutManager(HabitRuleSetActivity.this));
        habitSigninRecycler.setAdapter(habitSigninAdapter);
    }

    @OnClick({R.id.btnBack, R.id.btnSave})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnBack:
                // 返回事件
                setCloseParams();
                finishAfterTransition();
                break;
            case R.id.btnSave:

                if (DateUtils.compareDate(new Date(), DATA.getEndDt()) > 0) {
                    AlertUtils.showToast(this, R.string.habit_rule_set_out_of_range);
                    break;
                }

                AlertUtils.changeHabitRuleDialog(this, getResources().getString(R.string.alt_change_habit_rule), (dialog, which) -> {
                    // 保存事件
                    ServiceFactory.getInstance().getHabitService().saveHabitOrderRelate(DATA);
                    if (DATA_ID != 0) {
                        setCloseParams();
                    }
                    finishAfterTransition();
                });
                break;
        }
    }


    @Override
    public void onBackPressed() {
        setCloseParams();
        super.onBackPressed();
    }

    private void setCloseParams() {
        Intent intent = new Intent();
        intent.putExtra(PARAMS_POSITION, DATA_POSITION);
        intent.putExtra(PARAMS_KEY, orderId);
        setResult(RESULT_OK, intent);
    }

}
